<?php
/**
 * @link https://www.kancloud.cn/cleverstone/ymb2
 * @copyright Copyright (c) 2020 Yii Manager Software LLC
 */

use yii\helpers\Json;

/* ====== 选项卡构建器 ====== */
/** @var \yii\web\View $this View实例 */
/** @var \builder\tab\TabBuilder $context 上下文实例 */
/** @var array $tabItem tab项 */
/** @var array $extraJs 额外的JS脚本 */

$context = $this->context;
$initTabProp = '';
$tabSwitchMap = [];
?>
<script>
    !function (global, top) { "use strict";
        global.ym2App.controller("ym2.ctrl.<?= $context->id ?>", ["$scope", "ym2", "layui", function ($scope, ym2, layui) {
            var tabs = layui.tabs;
            var tabsId = "ym2_builder_<?= $context->id ?>";
            var initTabProp;

            // 选项卡切换
            tabs.on("afterChange(" + tabsId + ")", function (data) {
                var currentTabId = this.getAttribute('lay-id');
                var callback;
                switch (currentTabId) {
<?php foreach ($tabItem as $value): ?>
                    case "<?= $value['id'] ?>":
<?php if (!empty($value['reloadProperty'])): ?>
<?php $tabSwitchMap[$value['id']] = $value['reloadProperty']; ?>
<?php if ($value['selected']) $initTabProp = $value['reloadProperty']; ?>
                        callback = global.ym2BehaviorReqExport["<?= $value['reloadProperty'] ?>"];
                        if (ym2.typeOf(callback) === "function") {
                            callback.call();
                        }
<?php endif; ?>
                        break;
<?php endforeach; ?>
                }
            });

            // 初始化选项卡
            var tabSwitchMap = <?= Json::encode($tabSwitchMap) ?>;
            var layid = layui.hash().href;
            if (layid) {
                setTimeout(function () {
                    tabs.change(tabsId, layid);
                });
                initTabProp = tabSwitchMap[layid] || "";
            } else {
                initTabProp = "<?= $initTabProp ?>";
            }
            angular.element(function () {
                if (initTabProp && ym2.typeOf(global.ym2BehaviorReqExport[initTabProp]) === "function") {
                    global.ym2BehaviorReqExport[initTabProp].call();
                }
            });

            //额外的JS脚本
            <?= !empty($extraJs) ? implode("\n", $extraJs) : '' ?>

        }]);
    }(window, top);
</script>
